<?php

namespace app\admin\controller\zbtask;

use app\admin\logic\MoneyLogic;
use app\common\controller\Backend;
use app\common\library\task\ImportService;
use app\common\utils\Utils;
use think\Db;
use app\common\model\zbtask\Zbtask as TaskModel;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Import extends Backend
{
    protected $searchFields = 'real_name,identity_card';
    //做了数据限制
    protected $dataLimit = 'auth';
    protected $dataLimitField = 'task_id';
    protected $dataLimitFieldAutoFill = false;

    /**
     * 获取数据限制的管理员ID
     * 禁用数据限制时返回的是null
     * @return mixed
     */
    protected function getDataLimitAdminIds()
    {
        if (!$this->dataLimit) {
            return null;
        }
        if ($this->auth->isSuperAdmin() || TYPE == 0) {
            return null;
        }
        if (TYPE == 2) {
            $this->error('无权限浏览');
        }
        $task_ids = [];
        if (in_array($this->dataLimit, ['auth', 'personal'])) {
            $where['company_id'] = TYPE_ID;
            $task_ids = TaskModel::where($where)->column('id');
        }
        return $task_ids;
    }
    /**
     * Import模型对象
     * @var \app\common\model\zbtask\Import
     */
    protected $model = null;
    protected $modelValidate = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\zbtask\Import;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("moneyTypeList", $this->model->getMoneyTypeList());
        $this->view->assign("isImportList", $this->model->getIsImportList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['zbtask'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['zbtask'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','task_id','colorbg','month','year','real_name','identity_card','bank_card','mobile','money','type','status','msg','money_type','is_import']);
                $row->visible(['zbtask']);
                $month = MoneyLogic::instance()->getMoney($row['identity_card'], 'month', $row['zbtask']['createtime']);
                $year = MoneyLogic::instance()->getMoney($row['identity_card'], 'year', $row['zbtask']['createtime']);
                if ($row['is_import'] == 0) {
                    $month = Utils::processMoney($month, $row['money'], '+');
                    $year = Utils::processMoney($year, $row['money'], '+');
                }

                $row->month = $month;
                $row->year = $year;
                $row->colorbg = '';
                if ($row->month >= config('site.month_limit')) {
                    $row->colorbg = 'warning';
                }
                if ($row->year >= config('site.year_limit')) {
                    $row->colorbg = 'danger';
                }
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 确认提交正确数据
     */
    public function sureSubmit() {
        //当前是否为关联查询
        $this->relationSearch = true;
        $postData = $this->request->post();
        $ids = $postData['ids'];
        $where = [];
        if ($ids == 'all') {
            $this->request->get(['filter' => $postData['filter'], 'op' => $postData['op'], 'search'=> $postData['search']]);
            list($where) = $this->sureParams();
        } else {
            $where['import.id'] = ['in', $ids];
        }

        $list = $this->model
            ->with(['zbtask'])
            ->where($where)
            ->select();
        $list = collection($list)->toArray();
        //对数据进行过滤 然后导入数据库
        foreach ($list as $k => $v) {
            if ($v['status'] != 1) {
                $this->error('姓名为：'.$v['real_name'] . '的信息不正确，请修改后再提交');
            }

            //生成税率
            Db::startTrans();
            try {
                //对导入的数据惊醒
                ImportService::instance()->setData($v)->createUser()->createOrder()->insertData();
                //导入成功 修改导入 状态
                $this->model->where(['id'=> $v['id']])->setField('is_import', 1);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $msg = $this->model->where(['id'=> $v['id']])->value('msg');
                $msg = $msg . '/r/n' .$e->getMessage() . '。';
                $this->model->where(['id'=> $v['id']])->setField('msg', $msg);
                $this->error('姓名：' . $v['real_name'] . $e->getMessage());
            }
        }
        $this->success('提交成功');
    }
    protected function sureParams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        //批量导入 必须在某一个任务下面进行
        if (!isset($filter['task_id']) || !$filter['task_id']) {
            $this->error('全部导入情况下，必须首先选择一个任务');
        }
        $where = [];
        $tableName = '';
        if ($relationSearch) {
            if (!empty($this->model)) {
                $name = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
                $name = $this->model->getTable();
                $tableName = $name . '.';
            }
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$tableName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $tableName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        foreach ($filter as $k => $v) {
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $tableName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $where[] = "FIND_IN_SET('{$v}', " . ($relationSearch ? $k : '`' . str_replace('.', '`.`', $k) . '`') . ")";
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
                    break;
                case 'LIKE':
                case 'LIKE %...%':
                    $where[] = [$k, 'LIKE', "%{$v}%"];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }

        $where = function ($query) use ($where) {
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where];
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    //验证通过 置为正确
                    $params['status'] = 1;
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
